/**
 * Created by Administrator on 2017/6/27.
 */
var chart  = null;// 折线图
var socketPath ;
var xaxis;
var yaxis;
var zaxis;

$(function() {
    var canvas = document.getElementById('canvas');
    var inix =$("#canvas").width()/2;
    var iniy =$("#canvas").height()/2;
    console.log("否"+inix+iniy);
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(inix, iniy);
    }

    var poswebSocket = new WebSocket('ws://' + socketPath + '/websocket/001-POS' );
        poswebSocket.onerror = function (event) {			// socket错误响应事件
            onError(event);
        };
        poswebSocket.onopen = function (event) {			// socket开启响应事件
            onOpen(event);
        };
        poswebSocket.onmessage = function (event) {		// socket接收响应事件
            onMessage(event);
        };

        
});

function onOpen(event) {
}

function onError(event) {
    alert(event.data);
}

function onMessage(event) {
    console.log("是否"+event.data);
    var data = JSON.parse(event.data);
    postionarr=data.value.split(",");
    xaxis=parseFloat(postionarr[0]);
    yaxis=parseFloat(postionarr[1]);
    zaxis=parseFloat(postionarr[2]);
    console .log("位置"+position);
    console .log("x轴"+xaxis);
    console .log("y轴"+yaxis);
    var position=getposition(xaxis,yaxis,zaxis);
    console .log("位置"+position);
    draw(position);
}
function clearCanvas()
{
    var cxt=document.getElementById("canvas").getContext("2d");
    var inix =$("#canvas").width()/2;
    var iniy =$("#canvas").height()/2;
    cxt.clearRect(0,0,2*inix,2*iniy);
    var canvas = document.getElementById('canvas');
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(inix,iniy);}
}
function getposition(xaxis,yaxis,zaxis) {
    var inix =$("#canvas").width()/2;
    var iniy =$("#canvas").height()/2;
    var myselect=document.getElementById("axis");
    var index=myselect.selectedIndex;
    var txt=myselect.options[index].text;
    var position=new Array();
    console.log("这个"+txt+index);
    switch (txt){
        case "xy":
            var a=xaxis+inix;
            var b=-yaxis+iniy;
            break;
        case "xz":
            a=xaxis+inix;
            b=-zaxis+iniy;
            break;
        case "yz":
            a=yaxis+inix;
            b=-zaxis+iniy;
            break;
        case "xyz":
            a=xaxis+inix+zaxis /1.414;
            b=-yaxis+iniy -zaxis/1.414;
            console .log("ab"+a+","+b);
        default:
            break
    }
    position[0]=a;
    position[1]=b;
    return position;
    
}
function draw(position){
    var canvas = document.getElementById('canvas');
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        ctx.lineTo(position[0],position[1]);
        ctx.stroke()
    }
}

